package com.binaryTree;

import java.util.LinkedList;
import java.util.Queue;

public class PopulatingNextRightPointersinEachNodeII0228_117 {
    public Node connect(Node root) {
        Queue<Node> que = new LinkedList<>();
        if(root != null) que.offer(root);

        while (!que.isEmpty()){
            int len = que.size();

            while (len>0){
                Node node = que.poll();
                if(node.left != null) que.offer(node.left);
                if(node.right != null) que.offer(node.right);

                if(len == 1) node.next = null;
                else node.next = que.peek();

                len--;
            }
        }

        return root;
    }
}


class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
